package util.utilitarioPersistencia;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public abstract class DAOJPA<T extends ObjetoPersistente> implements DAO<T> {

    //Obtém o factory a partir da unidade de persistência.
    protected static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("JPA");
    protected static EntityManager entityManager = entityManagerFactory.createEntityManager();

    @Override
    public T salvar(T obj) {

        try {
            entityManager.getTransaction().begin();
            if (obj.getId() == null) {
                entityManager.persist(obj);
            }
            else {
                obj = entityManager.merge(obj);
            }
            entityManager.getTransaction().commit();
        }
        catch (Exception e) {
            obj = null;
            System.err.println("Erro ao obter " + e);
        }
        return obj;
    }

    @Override
    public boolean excluir(T obj) {
        boolean confirm = true;

        try {
            entityManager.getTransaction().begin();
            entityManager.remove(obj);
            entityManager.getTransaction().commit();
        }
        catch (Exception e) {
            confirm = false;
            System.err.println("Erro ao excluir " + e);
        }
        return confirm;
    }

    //TODO tentar resolver a passagem do .class
    @Override
    public List<T> obter(Class<T> classe) {
        List<T> lista = null;
        try {
            Query query = entityManager.createQuery("SELECT t FROM " + classe.getSimpleName() + " t");
            lista = query.getResultList();
        }
        catch (Exception e) {
            lista = null;
            System.err.println("Erro ao obter " + e);
        }
        return lista;
    }
    
    @Override
        public T obterPorId(Class<T> classe, long id) {
        T obj = null;
        try {
            Query query = entityManager.createQuery("SELECT t FROM " + classe.getSimpleName() + " t where t.id = " + id);
            obj = (T) query.getSingleResult();
        }
        catch (Exception e) {
            System.err.println("Erro ao obter " + e);
        }
        return obj;
    }
}
